﻿using HealthcareSystem.API.Read.Application.Command.KnowledgeCommand;
using HealthcareSystem.API.Read.DTO.KnowledgeShowDto;
using HealthcareSystem.Domain.Knowleges;
using MediatR;
using WeekExam.PassPort.ErrorCode;
using WeekExam.PassPort.Infrastructure.Interface;

namespace HealthcareSystem.API.Read.Application.CommandHandel.KnowledgeCommandHandel
{
    public class ShowKnowledgeCommandHandel : IRequestHandler<ShowKnowledgeCommand, ApiResult<ApiPaging<List<KnowledgeDto>>>>
    {
        IBaseRepository<Knowledge> knowledgeHandler;

        public ShowKnowledgeCommandHandel(IBaseRepository<Knowledge> knowledgeHandler)
        {
            this.knowledgeHandler = knowledgeHandler;
        }
        /// <summary>
        /// 我的知识显示处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<ApiPaging<List<KnowledgeDto>>>> Handle(ShowKnowledgeCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<List<KnowledgeDto>>> result = new ApiResult<ApiPaging<List<KnowledgeDto>>>();
            result.Code = ResultCode.查询成功;
            result.Message = ResultCode.查询成功.ToString();

            var list = from a in knowledgeHandler.GetAll()
                       select new KnowledgeDto
                       {
                           KnowledgeId = a.KnowledgeId,
                           Theme = a.Theme,
                           Knowledgeopen = a.Knowledgeopen,
                           Entity = a.Entity,
                           KnowledgeStatus = a.KnowledgeStatus,
                           KnowledgeTime = a.KnowledgeTime,
                       };

            var totalCount = list.Count();
            var totalPage = (int)Math.Ceiling((totalCount * 1.0) / request.pageSize);
            list = list.OrderBy(x=>x.KnowledgeId).Skip((request.pageIndex-1)*request.pageSize).Take(request.pageSize);


            
            if (!string.IsNullOrEmpty(request.Theme))
            {
                list = list.Where(x => x.Theme == request.Theme);
            }

            
            if (!string.IsNullOrEmpty(request.Entity))
            {
                list = list.Where(x => x.Entity == request.Entity);
            }

            ApiPaging<List<KnowledgeDto>> paging = new ApiPaging<List<KnowledgeDto>>();
            paging.totalPage = totalPage;
            paging.totalCount = totalCount;
            paging.Data = list.ToList();
            result.Data = paging;

            return Task.FromResult(result);


        }
    }
}
